//
//  MainViewController.swift
//  8.31Dami微博
//
//  Created by 安静的大米 on 15/8/31.
//  Copyright © 2015年 Dami. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //添加子控制器
        addChildViewControllers()
        
        
    }

  
    private func addChildViewControllers(){
        
        addChildViewController(HomeTableViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(MessageTableViewController(), title: "消息", imageName: "tabbar_message_center")
        
        // 添加了一个空白的控制器
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(ProfileTableViewController(), title: "我", imageName: "tabbar_profile")
        
        
    }
    
    //设置中间的tabbar Item
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        setupComposedButton()
        
        
        
    }
    
    private func setupComposedButton(){
        let count = childViewControllers.count
        
        let w = tabBar.bounds.width / CGFloat(count)
        
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.frame.height)
        
        composedButton.frame = CGRectOffset(rect, 2 * w, 0)
        
        
        
        
        
        
    }
    
    

    //懒加载控件
    lazy var composedButton: UIButton = {
       let btn = UIButton()
        
        //设置图像
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        
        self.tabBar.addSubview(btn)
        //添加监听的方法
        btn.addTarget(self, action: "clickComposedButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        
        return btn
        
        
        
    }()
    
    @objc private func clickComposedButton(){
        
        
        
        print("asdf")
    }
    
    
    //添加独立的自控制器
   private func addChildViewController(vc: UIViewController,title: String,imageName: String) {
        vc.title = title;
        vc.tabBarItem.image = UIImage(named: imageName)
        
        
        //添加控制器
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
        
        
    }
    
    
}
